package scau.mis4.chanyulin.service;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import scau.mis4.chanyulin.dao.TempDao;
import scau.mis4.chanyulin.entity.Temp;
import scau.mis4.chanyulin.tools.utils.TimeUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by cyl on 2017/12/5.
 * 数据导出
 */
public class DataExportService {

    public static boolean exportAllDataToExcel(String exportPath) {
        // 表格标题
        String[] cellTitle = {"id", "温度1", "温度2", "温度3", "温度4", "温度5", "温度6", "平均温度", "时间"};
        // 需要导出的数据
        List<Temp> dataList = TempDao.getAll();
        // 声明一个工作薄
        XSSFWorkbook workBook;
        workBook = new XSSFWorkbook();
        // 生成一个表格
        XSSFSheet sheet = workBook.createSheet();
        workBook.setSheetName(0,"温度数据");
        // 创建表格标题行（第一行）
        XSSFRow titleRow = sheet.createRow(0);
        for (int i = 0; i < cellTitle.length; i++) {
            titleRow.createCell(i).setCellValue(cellTitle[i]);
        }
        // 设置列宽
        sheet.setColumnWidth(0, 1750);
        sheet.setColumnWidth(8, 5750);
        // 插入需导出的数据
        DateFormat translator = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i=0; i < dataList.size(); i++) {
            XSSFRow row = sheet.createRow(i + 1);
            Temp temp = dataList.get(i);
            row.createCell(0).setCellValue(temp.getId());
            row.createCell(1).setCellValue(temp.getTemp1());
            row.createCell(2).setCellValue(temp.getTemp2());
            row.createCell(3).setCellValue(temp.getTemp3());
            row.createCell(4).setCellValue(temp.getTemp4());
            row.createCell(5).setCellValue(temp.getTemp5());
            row.createCell(6).setCellValue(temp.getTemp6());
            row.createCell(7).setCellValue(temp.getAvg());
            row.createCell(8).setCellValue(translator.format(temp.getTime()));
        }
        // 目标导出文件
        String fileName = "温度数据导出_" + TimeUtils.toChineseYMDHMS(System.currentTimeMillis()) + ".xlsx";
        String finalPath = exportPath + "\\" + fileName;
        File file = new File(finalPath);
        // 文件输出流
        try {
            FileOutputStream outStream = new FileOutputStream(file);
            workBook.write(outStream);
            outStream.flush();
            outStream.close();
            System.out.println("[导出数据] 导出Excel成功，文件导出路径：" + exportPath + "\\" + fileName);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("[导出数据] 导出Excel出现异常");
            return false;
        }
    }

}
